package com.chenhan.common.core.support;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 在 MyBatis Plus 的 BaseMapper 的基础上拓展，提供更多的能力
 */
public interface BaseMapperX<T> extends BaseMapper<T> {
    Log log = LogFactory.getLog(BaseMapperX.class);
    int DEFAULT_BATCH_SIZE = 1000;

    default PageResult<T> queryPage(Page page,Map<String, Object> queryMap) {
        return PageResult.build(selectPage(page, getQueryWrapper(queryMap)));
    }

    default List<T> queryList(Map<String, Object> queryMap) {
        return selectList(getQueryWrapper(queryMap));
    }

    default T queryOne(Map<String, Object> queryMap) {
        return selectOne(getQueryWrapper(queryMap));
    }


    /**
     * 批量插入
     */
    default boolean insertBatch(Collection<T> entityList) {
        return insertBatch(entityList, DEFAULT_BATCH_SIZE);
    }

    /**
     * 批量更新
     */
    default boolean updateBatchById(Collection<T> entityList) {
        return updateBatchById(entityList, DEFAULT_BATCH_SIZE);
    }

    /**
     * 批量插入或更新
     */
    default boolean insertOrUpdateBatch(Collection<T> entityList) {
        return insertOrUpdateBatch(entityList, DEFAULT_BATCH_SIZE);
    }

    /**
     * 批量插入(包含限制条数)
     */
    default boolean insertBatch(Collection<T> entityList, int batchSize) {
        return Db.saveBatch(entityList,batchSize);
    }

    /**
     * 批量更新(包含限制条数)
     */
    default boolean updateBatchById(Collection<T> entityList, int batchSize) {
        return Db.updateBatchById(entityList,batchSize);
    }

    /**
     * 批量插入或更新(包含限制条数)
     */
    default boolean insertOrUpdateBatch(Collection<T> entityList, int batchSize) {
        return Db.saveOrUpdateBatch(entityList,batchSize);
    }

    default QueryWrapper<T> getQueryWrapper(Map<String, Object> parm){
        QueryWrapper<T> qw = new QueryWrapper<>();
        SqlKeyword.buildCondition(parm, qw);
        return qw;
    }


//    default Class<M> currentMapperClass() {
//        return (Class<M>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseMapperY.class, 0);
//    }

//    default Class<T> currentModelClass() {
//        return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseMapperY.class, 1);
//    }

}
